#include "Triangle.hpp"
#include "rasterizer.hpp"
#include <eigen3/Eigen/Eigen>
#include <iostream>
#include <opencv2/opencv.hpp>
#include <cmath>

constexpr double MY_PI = 3.1415926;

Eigen::Matrix4f get_view_matrix(Eigen::Vector3f eye_pos)
{
    Eigen::Matrix4f view = Eigen::Matrix4f::Identity();

    Eigen::Matrix4f translate;
    translate << 1, 0, 0, -eye_pos[0], 0, 1, 0, -eye_pos[1], 0, 0, 1,
        -eye_pos[2], 0, 0, 0, 1;

    view = translate * view;

    return view;
}

Eigen::Matrix4f get_model_matrix(float rotation_angle)
{
    Eigen::Matrix4f model = Eigen::Matrix4f::Identity();

    // TODO: Implement this function
    // Create the model matrix for rotating the triangle around the Z axis.
    // Then return it.

    rotation_angle = rotation_angle / 180 * M_PI;

    //绕z轴旋转就是z坐标保持不变，x,y坐标和2D的旋转矩阵相同
    float cos_theta = std::cos(rotation_angle);
    float sin_theta = std::sin(rotation_angle);
    model << cos_theta, -sin_theta, 0, 0,
             sin_theta, cos_theta, 0, 0,
             0, 0, 1, 0,
             0, 0, 0, 1;

    return model;
}

Eigen::Matrix4f get_rotation(Vector3f axis, float angle) {
    float alpha = angle / 180 * M_PI;
    float cos_alpha = std::cos(alpha);

    Eigen::Matrix3f rotation = Eigen::Matrix3f::Identity(), t;
    rotation *= cos_alpha;

    t = (1 - cos_alpha) * axis * axis.transpose();

    rotation += t;

    t << 0, -axis.z(), axis.y(),
         axis.z(), 0, -axis.x(),
         -axis.y(), axis.x(), 0;

    t *= std::sin(alpha);

    rotation += t;

    Eigen::Matrix4f ret = Eigen::Matrix4f::Identity();
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            ret(i, j) = rotation(i, j);
        }
        ret(i, 3) = 0;
    }

    return ret;

}

Eigen::Matrix4f get_projection_matrix(float eye_fov, float aspect_ratio,
                                      float zNear, float zFar)
{
    // Students will implement this function

    Eigen::Matrix4f projection = Eigen::Matrix4f::Identity();

    // TODO: Implement this function
    // Create the projection matrix for the given parameters.
    // Then return it.
    float n = -zNear, f = -zFar, y, x;
    eye_fov /= 2;
    y = zNear * std::tan(eye_fov / 180 * M_PI);
    x = aspect_ratio * y;


    Eigen::Matrix4f perspctive, orthographic, translation;

    //首先通过变换将透视投影转换为正交投影
    perspctive << n, 0, 0, 0,
                  0, n, 0, 0,
                  0, 0, n + f, -n * f,
                  0, 0, 1, 0;

    //正交投影的缩放变换，变成一个[-1,1]^3的立方体
    orthographic << 1 / x, 0, 0, 0,
                    0, 1 / y, 0, 0,
                    0, 0, 2 / (n - f), 0,
                    0, 0, 0, 1;

    //正交投影首先进行平移，将坐标原点平移到(0, 0)处
    translation <<  1, 0, 0, 0,
                    0, 1, 0, 0,
                    0, 0, 1, -(n + f) / 2,
                    0, 0, 0, 1;

    orthographic *= translation;

    projection = orthographic * perspctive;


    return projection;
}

int main(int argc, const char** argv)
{
    float angle = 0;
    bool command_line = false;
    std::string filename = "output.png";

    if (argc >= 3) {
        command_line = true;
        angle = std::stof(argv[2]); // -r by default
        if (argc == 4) {
            filename = std::string(argv[3]);
        }
        else
            return 0;
    }

    constexpr int width = 700, height = 700;

    rst::rasterizer r(width, height);

    Eigen::Vector3f eye_pos = {0, 0, 5};

    std::vector<Eigen::Vector3f> pos{{2, 0, -2}, {0, 2, -2}, {-2, 0, -2}};

    std::vector<Eigen::Vector3i> ind{{0, 1, 2}};

    auto pos_id = r.load_positions(pos);
    auto ind_id = r.load_indices(ind);

    int key = 0;
    int frame_count = 0;

    if (command_line) {
        r.clear(rst::Buffers::Color | rst::Buffers::Depth);

        r.set_model(get_model_matrix(angle));
        r.set_view(get_view_matrix(eye_pos));
        r.set_projection(get_projection_matrix(45, 1, 0.1, 50));

        r.draw(pos_id, ind_id, rst::Primitive::Triangle);
        cv::Mat image(width, height, CV_32FC3, r.frame_buffer().data());
        image.convertTo(image, CV_8UC3, 1.0f);

        cv::imwrite(filename, image);

        return 0;
    }


    while (key != 27) {
        r.clear(rst::Buffers::Color | rst::Buffers::Depth);

//        r.set_model(get_model_matrix(angle));
        Eigen::Vector3f axis;
        axis << 1, 0, 0;
        r.set_model(get_rotation(axis, angle));
        r.set_view(get_view_matrix(eye_pos));
        r.set_projection(get_projection_matrix(80, 1, 0.1, 50));

        r.draw(pos_id, ind_id, rst::Primitive::Triangle);

        cv::Mat image(width, height, CV_32FC3, r.frame_buffer().data());
        image.convertTo(image, CV_8UC3, 1.0f);
        cv::imshow("image", image);
        key = cv::waitKey(10);

        std::cout << "frame count: " << frame_count++ << '\n';

        if (key == 'a') {
            angle += 10;
        }
        else if (key == 'd') {
            angle -= 10;
        }
    }

    return 0;
}
